package com.tanhua.commons.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 推荐
 * 计算测灵魂答题的相似度
 * 欧几里距离算法
 *
 * @author larry
 */
public class Similarity {
    public Map<String, Double> rating_map = new HashMap<String, Double>();

    public double getsimilarity_bydim(Similarity u) {
        double sim = 0d;
        double common_items = 0;

        Iterator<String> rating_map_iterator = rating_map.keySet().iterator();
        while (rating_map_iterator.hasNext()) {
            String rating_map_iterator_key = rating_map_iterator.next();
            Iterator<String> u_rating_map_iterator = u.rating_map.keySet().iterator();
            while (u_rating_map_iterator.hasNext()) {
                String u_rating_map_iterator_key = u_rating_map_iterator.next();
                if (rating_map_iterator_key.equals(u_rating_map_iterator_key)) {
                    //相似度计数加一 
                    //求差值的平方和
                    common_items++;
                    sim += Math.pow((u.rating_map.get(u_rating_map_iterator_key) - this.rating_map.get(rating_map_iterator_key)), 2);
                    System.out.println("第一个sim:"+sim);
                }
            }
        }

        //如果等于零则无相同条目，返回sim=0即可 
        if (common_items > 0) {
            //相似度的范围在0-1之间//tanh取值范围-1到1 
            //0表示完全不相似 
            //1表示完全相似 
            //求平均后开跟 
            //乘上相同的数量占最大可能相同的数量的比重 
            sim = Math.sqrt(sim / common_items);
            sim = 1.0d - Math.tanh(sim);
            System.out.println("计算tanh之后的sim:"+sim);
            int max_common_items = Math.min(rating_map.size(), u.rating_map.size());
            sim = sim * (common_items / max_common_items);
            System.out.println("第二个sim:"+sim);
        }
        return sim;
    }

} 